package com.falcon.handler;

import cn.hutool.core.bean.BeanUtil;
import com.falcon.domain.po.LogPO;
import com.falcon.mapper.ILogMapper;
import com.swan.log.listener.ILogEventListener;
import com.swan.log.listener.LogInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/** 日志入库
 * @author zongf
 * @date 2024-02-04
 **/
@Slf4j
@Component
public class LogEventToDbListener implements ILogEventListener {

    @Autowired
    private ILogMapper logMapper;

    private int throwableStackMaxLength = 4000;

    @Override
    public void handle(LogInfo logInfo) {
        LogPO logPO = BeanUtil.copyProperties(logInfo, LogPO.class);

        // 处理字段超长
        if (Objects.nonNull(logInfo.getThrowableStack())) {
            if (logPO.getThrowableStack().length() > throwableStackMaxLength) {
                logPO.setThrowableStack(logPO.getThrowableStack().substring(0, throwableStackMaxLength));
            }
        }

        this.logMapper.insertNotNull(logPO);
    }

}
